package com.master_jpeg.trasformation.zoom;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGEncodeParam;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * Created by ivsh0613 on 20.02.14.
 */
public class TextZoom extends JZoom {


    @Override
    public void zoom() throws IOException {

        int quality = 80;
        BufferedImage resizedImage = new BufferedImage(thumbWidth,
                thumbHeight, imageType);
        Graphics2D graphics2D = resizedImage.createGraphics();
        graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
                RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        graphics2D.drawImage(this.getImage(), 0, 0, thumbWidth, thumbHeight, null);
        // Дублирующий метод с более быстрой работой
        //graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
        //        RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        //Более высокое качество по сравнению с остальными, но работает медленее
        //Image scaledImage = resizedImage.getScaledInstance(rect.width, rect.height,
        //        Image.SCALE_SMOOTH);
        BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(this.getOutFile()));
        JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
        JPEGEncodeParam encodeParam = encoder.
                getDefaultJPEGEncodeParam(resizedImage);

        quality = Math.max(0, Math.min(quality, 100));
        encodeParam.setQuality(quality / 100.0f, false);
        encoder.setJPEGEncodeParam(encodeParam);
        encoder.encode(resizedImage);
        out.close();
    }
}
